<?php

class Adminmodel extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    /* begin back-end */

    //check login
    function _check_login($session_key) {
        if (empty($_SESSION[$session_key])) {
            return false;
        } else {
            return true;
        }
    }

    //get session
    function _get_session($session_key) {
        if (isset($_SESSION[$session_key]))
            return $_SESSION[$session_key];
    }

    //get session
    function _set_session($session_key, $value) {
        $_SESSION[$session_key] = $value;
    }

    //remove session
    function _remove_session($session_key) {
        unset($_SESSION[$session_key]);
    }

    function _get_user_details($username) {
        $sql = "SELECT * FROM be_user WHERE user_name='" . $username . "' and status='1'";
        $db = $this->load->database('default', TRUE);
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = 0;
        return array($iRow_Count, $aRows);
    }

    //get common info: City

    function _get_city_list() {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * FROM city";
        $query = $db->query($sql);
        return $query->result();
    }

    // begin newscate

    function _get_news_cate_list() {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT cate1.cate_id AS parent_id, cate1.cate_name AS parent_name, cate2.*  
						FROM news_cate AS cate1
						RIGHT JOIN news_cate AS cate2 ON cate1.cate_id = cate2.parent_id;";
        $query = $db->query($sql);
        return $query->result();
    }

    function _get_newscate_detail($id) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * from news_cate WHERE cate_id=" . $id;
        $query = $db->query($sql);
        return $query->result();
    }

    function _insert_newscate($tablename, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->insert($tablename, $data);

        return $db->insert_id();
    }

    function _update_newscate($tablename, $primarykey, $primaryvalue, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->where($primarykey, $primaryvalue);
        $db->update($tablename, $data);
    }

    // begin faqcate

    function _get_faq_cate_list() {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * FROM faq_cate";
        $query = $db->query($sql);
        return $query->result();
    }

    function _get_faqcate_detail($id) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * from faq_cate WHERE cate_id=" . $id;
        $query = $db->query($sql);
        return $query->result();
    }

    function _insert_faqcate($tablename, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->insert($tablename, $data);
        return $db->insert_id();
    }

    function _update_faqcate($tablename, $primarykey, $primaryvalue, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->where($primarykey, $primaryvalue);
        $db->update($tablename, $data);
    }

    // begin advcate

    function _get_adv_cate_list() {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * FROM adv_cate";
        $query = $db->query($sql);
        return $query->result();
    }

    function _get_advcate_detail($id) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * from adv_cate WHERE cate_id=" . $id;
        $query = $db->query($sql);
        return $query->result();
    }

    function _insert_advcate($tablename, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->insert($tablename, $data);
        return $db->insert_id();
    }

    function _update_advcate($tablename, $primarykey, $primaryvalue, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->where($primarykey, $primaryvalue);
        $db->update($tablename, $data);
    }

    //begin adv (Rao Vặt)	
    function _get_adv_list($limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT count(adv_id) c FROM adv2013";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;
        $sql = "SELECT adv2013.*, adv_cate.cate_name,adv2013.city_id from adv2013
						inner join adv_cate on adv2013.adv_cate_id=adv_cate.cate_id
		 			  ORDER BY adv_id DESC LIMIT {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    function _get_adv_detail($id) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * from adv2013 WHERE adv_id=" . $id;
        $query = $db->query($sql);
        return $query->result();
    }

    function _update_adv($tablename, $primarykey, $primaryvalue, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->where($primarykey, $primaryvalue);
        $db->update($tablename, $data);
    }

    function _delete_adv($id) {
        $sql = "delete from adv2013 where adv_id='" . $id . "'";
        $db = $this->load->database('default', TRUE);
        $query = $db->query($sql);
        return "success";
    }

    function _search_adv_list($title, $cate_id, $create_date, $limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "select count(adv2013.adv_id) c FROM adv2013
						inner join city on adv2013.city_id=city.city_id
						inner join adv_cate on adv2013.adv_cate_id=adv_cate.cate_id
						where 1=1";
        if ($title != "")
            $sql.=" and adv2013.title like N'%" . $title . "%' ";
        if ($cate_id != "")
            $sql.=" and adv2013.adv_cate_id=" . $cate_id;
        if ($create_date != "")
            $sql.=" and date(adv2013.create_date)='" . $create_date . "' ";
        $sql.=" order by adv_id DESC;";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;

        $sql = "SELECT adv2013.*, city.city_name, adv_cate.cate_name from adv2013
						inner join city on adv2013.city_id=city.city_id
						inner join adv_cate on adv2013.adv_cate_id=adv_cate.cate_id 
						where 1=1";
        if ($title != "")
            $sql.=" and adv2013.title like N'%" . $title . "%' ";
        if ($cate_id != "")
            $sql.=" and adv2013.adv_cate_id=" . $cate_id;
        if ($create_date != "")
            $sql.=" and date(adv2013.create_date)='" . $create_date . "' ";
        $sql.=" order by adv_id DESC LIMIT {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    //FAQ
    //begin faq (Rao Vặt)	

    function _get_faq_list($limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT count(faq_id) c FROM faq";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;
        $sql = "SELECT faq.*, faq_cate.cate_name from faq
						inner join faq_cate on faq.faq_cate_id=faq_cate.cate_id
		 			  ORDER BY faq_id DESC LIMIT {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    function _get_faq_detail($id) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * from faq WHERE faq_id=" . $id;
        $query = $db->query($sql);
        return $query->result();
    }

    function _update_faq($tablename, $primarykey, $primaryvalue, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->where($primarykey, $primaryvalue);
        $db->update($tablename, $data);
    }

    function _delete_faq($id) {
        $sql = "delete from faq where faq_id='" . $id . "'";
        $db = $this->load->database('default', TRUE);
        $query = $db->query($sql);
        return "success";
    }

    function _search_faq_list($question, $cate_id, $create_date, $limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "select count(faq.faq_id) c FROM faq
						inner join faq_cate on faq.faq_cate_id=faq_cate.cate_id
						where 1=1";
        if ($question != "")
            $sql.=" and faq.question like N'%" . $question . "%' ";
        if ($cate_id != "")
            $sql.=" and faq.faq_cate_id=" . $cate_id;
        if ($create_date != "")
            $sql.=" and date(faq.create_date)='" . $create_date . "' ";
        $sql.=" order by faq_id DESC;";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;

        $sql = "SELECT faq.*, faq_cate.cate_name from faq
						inner join faq_cate on faq.faq_cate_id=faq_cate.cate_id 
						where 1=1";
        if ($question != "")
            $sql.=" and faq.question like N'%" . $question . "%' ";
        if ($cate_id != "")
            $sql.=" and faq.faq_cate_id=" . $cate_id;
        if ($create_date != "")
            $sql.=" and date(faq.create_date)='" . $create_date . "' ";
        $sql.=" order by faq_id DESC LIMIT {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    function _insert_faq($tablename, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->insert($tablename, $data);
        return $db->insert_id();
    }

    // begin news

    function _get_url_of_parent_cate($cate_id) {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT url FROM news_cate WHERE cate_id=(SELECT parent_id FROM news_cate WHERE cate_id=" . $cate_id . ")";
        $query = $db->query($sql);
        $aRows = $query->result();
        if (count($aRows) > 0)
            return $aRows[0]->url;
        else
            return "";
    }

    function _get_news_list($limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT count(news_id) c FROM news";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;
        $sql = "SELECT news.*, news_cate.cate_name FROM news
						inner join news_cate on news_cate.cate_id = news.cate_id
		 			  ORDER BY news_id DESC LIMIT {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    function _get_news_detail($id) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * from news WHERE news_id=" . $id;
        $query = $db->query($sql);
        return $query->result();
    }

    function _insert_news($tablename, $data) {
        //mysql_query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->insert($tablename, $data);
        return $db->insert_id();
    }

    function _update_news($tablename, $primarykey, $primaryvalue, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->where($primarykey, $primaryvalue);
        $db->update($tablename, $data);
    }

    function _search_news_list($title, $cate_id, $create_date, $limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "select count(news.news_id) c FROM news
						inner join news_cate on news_cate.cate_id = news.cate_id
						where 1=1";
        if ($title != "")
            $sql.=" and news.title like N'%" . $title . "%' ";
        if ($cate_id != "")
            $sql.=" and news.cate_id=" . $cate_id;
        if ($create_date != "")
            $sql.=" and date(news.create_date)='" . $create_date . "' ";
        $sql.=" order by news_id DESC;";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;

        $sql = "select news.*, news_cate.cate_name FROM news
						inner join news_cate on news_cate.cate_id = news.cate_id
						where 1=1";
        if ($title != "")
            $sql.=" and news.title like N'%" . $title . "%' ";
        if ($cate_id != "")
            $sql.=" and news.cate_id=" . $cate_id;
        if ($create_date != "")
            $sql.=" and date(news.create_date)='" . $create_date . "' ";
        $sql.=" order by news_id DESC LIMIT {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    function _delete_news($id) {
        $sql = "delete from news where news_id='" . $id . "'";
        $db = $this->load->database('default', TRUE);
        $query = $db->query($sql);
        return "success";
    }

    function _crop_image($org_file, $x, $y, $w, $h, $num) {
        //begin crop:
        list($width, $height) = getimagesize(IMAGE_ROOT . $org_file);
        $ext = $this->findexts(IMAGE_ROOT . $org_file);
        if ($ext == "gif")
            $source = imagecreatefromgif(IMAGE_ROOT . $org_file);
        elseif ($ext == "jpg")
            $source = imagecreatefromjpeg(IMAGE_ROOT . $org_file);
        elseif ($ext == "png")
            $source = imagecreatefrompng(IMAGE_ROOT . $org_file);
        else
            return "";
        $filename = $this->findname($org_file) . "_thumb" . $num . "_" . time() . "." . $ext;
        //thumb image by crop info
        $large = imagecreatetruecolor($w, $h);
        $large_name = substr($filename, 0, strlen($filename) - 4) . '.jpg';
        imagecopyresized($large, $source, 0, 0, $x, $y, $w, $h, $w, $h);
        imagejpeg($large, IMAGE_ROOT . $large_name, 100);
        return $large_name;
    }

    //chỉ dành cho VBPQ
    function save_file($id, $upload_path, $upload_control_name) {
        $filename = "";
        //echo "\$_FILES[$upload_control_name][\"type\"]=".$_FILES[$upload_control_name]["type"];exit;
        if ($_FILES[$upload_control_name]["error"] > 0) {
            $filename = ""; //error
        } else {
            $ext = $this->findexts($_FILES[$upload_control_name]['name']);
            $filename = $this->findname($_FILES[$upload_control_name]["name"]) . "_" . time() . $id . "." . $ext;
            //echo "\$upload_path=".$upload_path."<br>";
            //echo "\$_FILES[$upload_control_name][\"type\"]=".$_FILES[$upload_control_name]["type"]."<br>";
            //echo "\$filename=".$filename."<br>";
            //exit;
            if (file_exists(IMAGE_ROOT . IMAGE_DIR . $upload_path . $filename)) {
                echo ""; // $_FILES["image1"]["name"] already exists. 
            } else {
                move_uploaded_file($_FILES[$upload_control_name]["tmp_name"], IMAGE_ROOT . IMAGE_DIR . $upload_path . $filename);
            }
        }
        if (!file_exists(IMAGE_ROOT . IMAGE_DIR . $upload_path . $filename))
            return "";
        return array($filename, $_FILES[$upload_control_name]["type"], IMAGE_DIR . $upload_path . $filename);
    }

    function save_image($id, $upload_path, $upload_control_name) {
        $filename = "";
        if ((($_FILES[$upload_control_name]["type"] == "image/gif") || ($_FILES[$upload_control_name]["type"] == "image/jpeg") || ($_FILES[$upload_control_name]["type"] == "image/pjpeg")) && ($_FILES[$upload_control_name]["size"] < 1020000)) {
            if ($_FILES[$upload_control_name]["error"] > 0) {
                $filename = ""; //error
            } else {
                $ext = $this->findexts($_FILES[$upload_control_name]['name']);
                $filename = $this->findname($_FILES[$upload_control_name]["name"]) . "_" . time() . $id . "." . $ext;
                if (file_exists(IMAGE_ROOT . IMAGE_DIR . $upload_path . $filename)) {
                    echo ""; // $_FILES["image1"]["name"] already exists. 
                } else {
                    move_uploaded_file($_FILES[$upload_control_name]["tmp_name"], IMAGE_ROOT . IMAGE_DIR . $upload_path . $filename);
                }
            }
        }
        if (!file_exists(IMAGE_ROOT . IMAGE_DIR . $upload_path . $filename))
            return "";
        return array($filename, $_FILES[$upload_control_name]["type"], IMAGE_DIR . $upload_path . $filename);
    }

    function save_image_thumb($id, $org_file, $filename, $file_type, $upload_path, $image_x_size, $image_y_size, $newfilename_subfix) {
        /* ------------- Get new sizes --------------------- */
        list($width, $height) = getimagesize($org_file);
        if ($width < 50 || $height < 50)
            return "";
        //   large
        if ($image_x_size < $width) {
            $large_width = $image_x_size;
            $large_height = $image_y_size; //round($height * $image_y_size/$width);
        } else {
            $large_width = $width;
            $large_height = $height;
        }
        /* ------------- END: Get new sizes ---------------- */
        // Load
        if ($file_type == "image/gif")
            $source = imagecreatefromgif($org_file);
        elseif ($file_type == "image/pjpeg" || $file_type == "image/jpeg")
            $source = imagecreatefromjpeg($org_file);
        elseif ($file_type == "image/x-png" || $file_type == "image/png")
            $source = imagecreatefrompng($org_file);
        else
            return "";

        // new images
        $newfilename = substr($filename, 0, strlen($filename) - 4) . '.jpg';
        $large = imagecreatetruecolor($large_width, $large_height);
        $large_name = IMAGE_DIR . $upload_path . time() . $id . $image_x_size . $image_y_size . $newfilename_subfix . '_' . $newfilename;
        imagecopyresized($large, $source, 0, 0, 0, 0, $large_width, $large_height, $width, $height);
        imagejpeg($large, IMAGE_ROOT . $large_name, 100);
        if (!file_exists(IMAGE_ROOT . $large_name))
            return "";
        return $large_name;
    }

    function findexts($filename) {
        $filename = strtolower($filename);
        $exts = substr($filename, strrpos($filename, '.') + 1);
        return $exts;
    }

    function findname($filename) {
        $filename = substr($filename, 0, strrpos($filename, '.'));
        return $filename;
    }

    function _delete_image_null($id, $image_num) {
        $db = $this->load->database('default', TRUE);
        $sql = " UPDATE `product` SET image{$image_num}_thumb1=null, image{$image_num}_thumb2=null, image{$image_num}_thumb3=null, 
										image{$image_num}_thumb4=null, image{$image_num}_thumb5=null 
					   WHERE `product_id` = '" . $id . "'";
        $query = $db->query($sql);
    }

    //thong tin doanh nghiep:
    function _get_company_list($limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT count(company_adv_id) c FROM company_adv";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;
        $sql = "SELECT * FROM company_adv
		 			  ORDER BY company_adv_id DESC LIMIT {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    function _insert_company($tablename, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->insert($tablename, $data);

        return $db->insert_id();
    }

    function _update_company($tablename, $primarykey, $primaryvalue, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->where($primarykey, $primaryvalue);
        $db->update($tablename, $data);
    }

    function _get_company_detail($id) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * from company_adv WHERE company_adv_id=" . $id;
        $query = $db->query($sql);
        return $query->result();
    }

    function _delete_company($id) {
        $sql = "delete from company_adv where company_adv_id='" . $id . "'";
        $db = $this->load->database('default', TRUE);
        $query = $db->query($sql);
        return "success";
    }

    function _search_company_list($name, $create_date, $limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "select count(company_adv_id) c FROM company_adv
						where 1=1";
        if ($name != "")
            $sql.=" and company_adv_name like N'%" . $name . "%' ";
        if ($create_date != "")
            $sql.=" and date(create_date)='" . $create_date . "' ";
        $sql.=" order by company_adv_id DESC;";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;

        $sql = "select * FROM company_adv
						where 1=1";
        if ($name != "")
            $sql.=" and company_adv_name like N'%" . $name . "%' ";
        if ($create_date != "")
            $sql.=" and date(create_date)='" . $create_date . "' ";
        $sql.=" order by company_adv_id DESC LIMIT {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    function _get_be_user_list($limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT count(be_user_id) c FROM be_user";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;
        $sql = "SELECT be_user.* FROM be_user
		 			  ORDER BY be_user_id DESC LIMIT {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    function _get_be_user_detail($id) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * from be_user WHERE be_user_id=" . $id;
        $query = $db->query($sql);
        return $query->result();
    }

    function _insert_be_user($tablename, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->insert($tablename, $data);
    }

    function _update_be_user($tablename, $primarykey, $primaryvalue, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->where($primarykey, $primaryvalue);
        $db->update($tablename, $data);
    }

    function _search_be_user_list($name, $limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "select * FROM be_user where user_name like '%" . $name . "%'   
					  order by be_user_id desc limit {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array(count($result), $result);
    }

    function _delete_be_user($id) {
        $sql = "delete from be_user where be_user_id='" . $id . "'";
        $db = $this->load->database('default', TRUE);
        $query = $db->query($sql);
        return "success";
    }

    function _check_user_name($user_name) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $sql = "SELECT count(be_user_id) c FROM be_user where user_name='" . $user_name . "';";
        $db = $this->load->database('default', TRUE);
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;
        return $iRow_Count;
    }

    function _get_contact_us_list($limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT count(contact_us_id) c FROM contact_us";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;
        $sql = "SELECT contact_us.* FROM contact_us
		 			  ORDER BY contact_us_id DESC LIMIT {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    function _get_contact_us_detail($id) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT * from contact_us WHERE contact_us_id=" . $id;
        $query = $db->query($sql);
        return $query->result();
    }

    function _insert_contact_us($tablename, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->insert($tablename, $data);
    }

    function _update_contact_us($tablename, $primarykey, $primaryvalue, $data) {
        //$sql = $this->db->query("SET NAMES 'utf8'");
        $db = $this->load->database('default', TRUE);
        $db->where($primarykey, $primaryvalue);
        $db->update($tablename, $data);
    }

    function _search_contact_us_list($message, $limit_from, $limit_to) {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT count(contact_us_id) c FROM contact_us where message like '%" . $message . "%'";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;
        $sql = "select * FROM contact_us where message like '%" . $message . "%'   
					  order by contact_us_id desc limit {$limit_from},{$limit_to};";
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    function _delete_contact_us($id) {
        $sql = "delete from contact_us where contact_us_id='" . $id . "'";
        $db = $this->load->database('default', TRUE);
        $query = $db->query($sql);
        return "success";
    }

    function _write_log($header, $msg) {
        $filepath = LOG_PATH . 'log-admin-' . date('Y-m-d') . '.php';
        $message = '';

        if (!file_exists($filepath)) {
            $message .= "<" . "?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?" . ">\n\n";
            $message .= $header . "\n";
        }

        if (!$fp = @fopen($filepath, FOPEN_WRITE_CREATE)) {
            return FALSE;
        }

        $message .= date("Y-m-d H:i:s") . ' --> ' . $msg . "\n";

        flock($fp, LOCK_EX);
        fwrite($fp, $message);
        flock($fp, LOCK_UN);
        fclose($fp);

        @chmod($filepath, FILE_WRITE_MODE);
    }

    function _get_memcached_info($status) {
        $str = "";
        $str = $str . '<table width="60%" border="0" cellpadding="4" cellspacing="6" bgcolor="#CED3FF" style="margin:auto; line-height:24px;">';
        $str = $str . "<tr><td align=\"center\" style='font-weight:bold; font-size:18px;'>Nội dung</td><td style='font-size:18px;font-weight:bold;'>Giá trị</td></tr>";
        $str = $str . "<tr><td>Memcached server <b>IP:Port</b></td><td> <b>" . MEMCACHED_IP . ":" . MEMCACHED_PORT . "</b></td></tr>";
        if (isset($status ["version"]))
            $str = $str . "<tr><td>Memcache Server version:</td><td> " . $status ["version"] . "</td></tr>";
        if (isset($status ["pid"]))
            $str = $str . "<tr><td>Process id of this server process </td><td>" . $status ["pid"] . "</td></tr>";
        if (isset($status ["uptime"]))
            $str = $str . "<tr><td>Number of seconds this server has been running </td><td>" . $status ["uptime"] . "</td></tr>";
        if (isset($status ["rusage_user"]))
            $str = $str . "<tr><td>Accumulated user time for this process </td><td>" . $status ["rusage_user"] . " seconds</td></tr>";
        if (isset($status ["rusage_system"]))
            $str = $str . "<tr><td>Accumulated system time for this process </td><td>" . $status ["rusage_system"] . " seconds</td></tr>";
        if (isset($status ["total_items"]))
            $str = $str . "<tr><td><b>Total number of items</b> stored by this server ever since it started </td><td>" . $status ["total_items"] . "</td></tr>";
        if (isset($status ["curr_connections"]))
            $str = $str . "<tr><td>Number of open connections </td><td>" . $status ["curr_connections"] . "</td></tr>";
        if (isset($status ["total_connections"]))
            $str = $str . "<tr><td>Total number of connections opened since the server started running </td><td>" . $status ["total_connections"] . "</td></tr>";
        if (isset($status ["connection_structures"]))
            $str = $str . "<tr><td>Number of connection structures allocated by the server </td><td>" . $status ["connection_structures"] . "</td></tr>";
        if (isset($status ["cmd_get"]))
            $str = $str . "<tr><td>Cumulative number of retrieval requests </td><td>" . $status ["cmd_get"] . "</td></tr>";
        if (isset($status ["cmd_set"]))
            $str = $str . "<tr><td> Cumulative number of storage requests </td><td>" . $status ["cmd_set"] . "</td></tr>";
        if (isset($status ["cmd_get"]) && $status ["cmd_get"] > 0) {
            $percCacheHit = ((real) $status ["get_hits"] / (real) $status ["cmd_get"] * 100);
            $percCacheHit = round($percCacheHit, 3);
            $percCacheMiss = 100 - $percCacheHit;
            $str = $str . "<tr><td><b>Number of keys</b> that have been requested and found present </td><td>" . $status ["get_hits"] . " ($percCacheHit%)</td></tr>";
            $str = $str . "<tr><td><b>Number of items</b> that have been requested and not found </td><td>" . $status ["get_misses"] . "($percCacheMiss%)</td></tr>";
        } else {
            $str = $str . "<tr><td><b>Number of keys</b> that have been requested and found present </td><td>" . $status ["get_hits"] . "</td></tr>";
            $str = $str . "<tr><td><b>Number of items</b> that have been requested and not found </td><td>" . $status ["get_misses"] . "</td></tr>";
        }

        $MBRead = (real) $status["bytes_read"] / (1024 * 1024);

        $str = $str . "<tr><td>Total number of bytes read by this server from network </td><td>" . $MBRead . " Mega Bytes</td></tr>";
        $MBWrite = (real) $status["bytes_written"] / (1024 * 1024);
        $str = $str . "<tr><td>Total number of bytes sent by this server to network </td><td>" . $MBWrite . " Mega Bytes</td></tr>";
        $MBSize = (real) $status["limit_maxbytes"] / (1024 * 1024);
        $str = $str . "<tr><td>Number of bytes this server is allowed to use for storage.</td><td>" . $MBSize . " Mega Bytes</td></tr>";
        $str = $str . "<tr><td>Number of valid items removed from cache to free memory for new items.</td><td>" . $status ["evictions"] . "</td></tr>";

        $str = $str . "</table>";

        return $str;
    }

    // hàm nay để test nested array
    function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL) {
        $do_dump_indent = "<span style='color:#eeeeee;'>|</span> &nbsp;&nbsp; ";
        $reference = $reference . $var_name;
        $keyvar = 'the_do_dump_recursion_protection_scheme';
        $keyname = 'referenced_object_name';

        if (is_array($var) && isset($var[$keyvar])) {
            $real_var = &$var[$keyvar];
            $real_name = &$var[$keyname];
            $type = ucfirst(gettype($real_var));
            echo "$indent$var_name <span style='color:#a2a2a2'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
        } else {
            $var = array($keyvar => $var, $keyname => $reference);
            $avar = &$var[$keyvar];

            $type = ucfirst(gettype($avar));
            if ($type == "String")
                $type_color = "<span style='color:green'>";
            elseif ($type == "Integer")
                $type_color = "<span style='color:red'>";
            elseif ($type == "Double") {
                $type_color = "<span style='color:#0099c5'>";
                $type = "Float";
            } elseif ($type == "Boolean")
                $type_color = "<span style='color:#92008d'>";
            elseif ($type == "NULL")
                $type_color = "<span style='color:black'>";

            if (is_array($avar)) {
                $count = count($avar);
                echo "$indent" . ($var_name ? "$var_name => " : "") . "<span style='color:#a2a2a2'>$type ($count)</span><br>$indent(<br>";
                $keys = array_keys($avar);
                foreach ($keys as $name) {
                    $value = &$avar[$name];
                    $this->do_dump($value, "['$name']", $indent . $do_dump_indent, $reference);
                }
                echo "$indent)<br>";
            } elseif (is_object($avar)) {
                echo "$indent$var_name <span style='color:#a2a2a2'>$type</span><br>$indent(<br>";
                foreach ($avar as $name => $value)
                    $this->do_dump($value, "$name", $indent . $do_dump_indent, $reference);
                echo "$indent)<br>";
            } elseif (is_int($avar))
                echo "$indent$var_name = <span style='color:#a2a2a2'>$type(" . strlen($avar) . ")</span> $type_color$avar</span><br>";
            elseif (is_string($avar))
                echo "$indent$var_name = <span style='color:#a2a2a2'>$type(" . strlen($avar) . ")</span> $type_color\"$avar\"</span><br>";
            elseif (is_float($avar))
                echo "$indent$var_name = <span style='color:#a2a2a2'>$type(" . strlen($avar) . ")</span> $type_color$avar</span><br>";
            elseif (is_bool($avar))
                echo "$indent$var_name = <span style='color:#a2a2a2'>$type(" . strlen($avar) . ")</span> $type_color" . ($avar == 1 ? "TRUE" : "FALSE") . "</span><br>";
            elseif (is_null($avar))
                echo "$indent$var_name = <span style='color:#a2a2a2'>$type(" . strlen($avar) . ")</span> {$type_color}NULL</span><br>";
            else
                echo "$indent$var_name = <span style='color:#a2a2a2'>$type(" . strlen($avar) . ")</span> $avar<br>";

            $var = $var[$keyvar];
        }
    }

    //get news auto from db
    function _get_news_auto_from_db($page_index, $page_size) {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT count(id) c FROM news_auto WHERE status=0";
        $query = $db->query($sql);
        $aRows = $query->result();
        $iRow_Count = $aRows[0]->c;

        if ($page_index == 0 && $page_size == 0) {
            $sql = "SELECT * FROM news_auto
                    WHERE status=0 
                    ORDER BY id DESC";
        } else {
            $sql = "SELECT * FROM news_auto
                    WHERE status=0 
                    ORDER BY id DESC 
                    LIMIT " . $page_index . "," . $page_size;
        }
        $query = $db->query($sql);
        $result = $query->result();
        return array($iRow_Count, $result);
    }

    //insert news auto to db
    function _insert_news_to_db($tablename, $data) {
        $db = $this->load->database('default', TRUE);
        $result = $db->insert_batch($tablename, $data);
        return $result;
    }

    //check news url lastest
    function _get_news_url_lastest($original_news) {
        $db = $this->load->database('default', TRUE);
        $sql = "SELECT url_lastest FROM news_auto_last 
                    where news_url=?";
        $query = $db->query($sql, array($original_news));
        $result = $query->result();

        return $result;
    }

    //update news url lastest
    function _update_url_lastest_by_original_news($url_lastest, $original_news) {
        $db = $this->load->database('default', TRUE);
        $data = array(
            'url_lastest' => $url_lastest
        );
        $db->where('news_url', $original_news);
        $result = $db->update('news_auto_last', $data);

        return $result;
    }

    //insert news url lastest without db
    function _insert_url_lastest($url_lastest, $original_news) {
        $db = $this->load->database('default', TRUE);
        $data = array(
            'url_lastest' => $url_lastest,
            'news_url' => $original_news
        );
        $result = $db->insert('news_auto_last', $data);

        return $result;
    }

    //delete news auto
    function _delete_news_auto($newsId) {
        $db = $this->load->database('default', TRUE);
        $result = $db->delete('news_auto', array('id' => $newsId));
        return $result;
    }

    //get news auto by id
    function _get_news_auto_by_id($newsId) {
        $db = $this->load->database('default', TRUE);
        $query = $db->get_where('news_auto', array('id' => $newsId));
        $result = $query->result();
        return $result;
    }

    //update status news
    function _update_status_news_auto($newsId, $status) {
        $db = $this->load->database('default', TRUE);
        $db->where('id', $newsId);
        $result = $db->update('news_auto', array('status' => $status));
        return $result;
    }

    //get video list
    function _get_video_from_db($pageIndex, $pageSize) {
        $db = $this->load->database('default', TRUE);
        $count = $db->count_all('video');

        $query = $db->get('video', $pageSize, $pageIndex);
        $result = $query->result();
        return array($count, $result);
    }

    //delete video
    function deleteVideo($videoId) {
        $db = $this->load->database('default', TRUE);
        $result = $db->delete('video', array('video_id' => $videoId));
        return $result;
    }

    //get lastest video
    function getLastestVideo() {
        $db = $this->load->database('default', TRUE);
        $db->order_by("video_id", "desc");
        $query = $db->get('video', 1, 0);
        $result = $query->result();
        return $result;
    }

    //insert video to db
    function _insert_video_to_db($data) {
        $data_insert = array_reverse($data);
        $db = $this->load->database('default', TRUE);
        $result = $db->insert_batch("video", $data_insert);
        return $result;
    }

    //get all cate of customs procedures
    function _get_all_cate_customs() {
        $db = $this->load->database('default', TRUE);
        $db->order_by("cate_id", "asc");
        $query = $db->get('customs_procedures_cate');
        $result = $query->result();
        return $result;
    }

    function get_all_cate_forwarding() {
        $db = $this->load->database('default', TRUE);
        $db->order_by("order", "asc");
        $query = $db->get('forwarding_cate');
        $result = $query->result();
        return $result;
    }

    function get_all_cate_knowledge() {
        $db = $this->load->database('default', TRUE);
        $db->order_by("order", "asc");
        $query = $db->get('knowledge_cate');
        $result = $query->result();
        return $result;
    }

    //get customs procedures item
    function _get_customs_procedures($customs_name, $customs_cate, $page_size, $page_index) {
        $db = $this->load->database('default', TRUE);

        if ($customs_name != "") {
            $db->like('customs_name', $customs_name);
        }

        if ($customs_cate != 0) {
            $query = $db->get_where("customs_procedures", array("customs_cate" => $customs_cate));
        } else {
            $query = $db->get('customs_procedures');
        }

        $result = $query->result();
        $count = sizeof($result);

        if ($customs_name != "") {
            $db->like('customs_name', $customs_name);
        }

        if ($customs_cate != 0) {
            $db->get_where("customs_procedures", array("customs_cate" => $customs_cate));
        }

        if ($customs_cate != 0) {
            $query = $db->get_where("customs_procedures", array("customs_cate" => $customs_cate), $page_size, $page_index);
        } else {
            $query = $db->get('customs_procedures', $page_size, $page_index);
        }
        $result = $query->result();
        return array($count, $result);
    }

    function get_forwarding_articles($title, $cate, $page_size, $page_index) {
        $db = $this->load->database('default', TRUE);

        if ($title != "") {
            $db->like('title', $title);
        }

        if ($cate != 0) {
            $query = $db->get_where("forwarding", array("cate" => $cate));
        } else {
            $query = $db->get('forwarding');
        }

        $count = $query->num_rows();

        if ($title != "") {
            $db->like('title', $title);
        }

        if ($cate != 0) {
            $db->get_where("forwarding", array("cate" => $cate));
        }

        if ($cate != 0) {
            $query = $db->get_where("forwarding", array("cate" => $cate), $page_size, $page_index);
        } else {
            $query = $db->get('forwarding', $page_size, $page_index);
        }
        $result = $query->result();
        return array($count, $result);
    }

    function get_knowledge_articles($title, $cate, $page_size, $page_index) {
        $db = $this->load->database('default', TRUE);

        if ($title != "") {
            $db->like('title', $title);
        }

        if ($cate != 0) {
            $query = $db->get_where("knowledge", array("cate" => $cate));
        } else {
            $query = $db->get('knowledge');
        }

        $count = $query->num_rows();

        if ($title != "") {
            $db->like('title', $title);
        }

        if ($cate != 0) {
            $db->get_where("knowledge", array("cate" => $cate));
        }

        if ($cate != 0) {
            $query = $db->get_where("knowledge", array("cate" => $cate), $page_size, $page_index);
        } else {
            $query = $db->get('knowledge', $page_size, $page_index);
        }
        $result = $query->result();
        return array($count, $result);
    }

    //insert customs procedures
    function _insert_customs_procedures($customs_name, $customs_manager, $customs_dv, $customs_url, $customs_content, $customs_cate) {
        $db = $this->load->database('default', TRUE);
        $data = array(
            'customs_name' => $customs_name,
            'customs_manager' => $customs_manager,
            'customs_dv' => $customs_dv,
            'customs_url' => $customs_url,
            'customs_content' => $customs_content,
            'customs_cate' => $customs_cate,
        );
        $result = $db->insert('customs_procedures', $data);
        return $result;
    }

    function insert_forwarding_article($title, $url, $content, $cate) {
        $db = $this->load->database('default', TRUE);
        $data = array(
            'title' => $title,
            'url' => $url,
            'content' => $content,
            'cate' => $cate,
        );
        $result = $db->insert('forwarding', $data);

        $sql = "update forwarding set `order` = id where `order` is null;";
        $db->query($sql);

        return $result;
    }

    function insert_knowledge_article($title, $url, $content, $cate) {
        $db = $this->load->database('default', TRUE);
        $data = array(
            'title' => $title,
            'url' => $url,
            'content' => $content,
            'cate' => $cate,
        );
        $result = $db->insert('knowledge', $data);

        $sql = "update knowledge set `order` = id where `order` is null;";
        $db->query($sql);

        return $result;
    }

    //get customs procedures by id
    function _get_customs_by_id($customs_id) {
        $db = $this->load->database('default', TRUE);
        $query = $db->get_where("customs_procedures", array("customs_id" => $customs_id));
        $result = $query->result();
        return $result;
    }

    function get_forwarding_article_by_id($id) {
        $db = $this->load->database('default', TRUE);
        $query = $db->get_where("forwarding", array("id" => $id));
        $result = $query->result();
        return $result;
    }

    function get_knowledge_article_by_id($id) {
        $db = $this->load->database('default', TRUE);
        $query = $db->get_where("knowledge", array("id" => $id));
        $result = $query->result();
        return $result;
    }

    //update customs
    function _update_customs_procedures($customs_id, $customs_name, $customs_manager, $customs_dv, $customs_content, $customs_cate) {
        $db = $this->load->database('default', TRUE);
        $data = array(
            'customs_name' => $customs_name,
            'customs_manager' => $customs_manager,
            'customs_dv' => $customs_dv,
            'customs_content' => $customs_content,
            'customs_cate' => $customs_cate
        );
        $db->where('customs_id', $customs_id);
        $result = $db->update('customs_procedures', $data);
        return $result;
    }

    function update_forwarding_article($id, $title, $content, $cate, $order) {
        if ($order <= 0) {
            $order = $id;
        }
        $db = $this->load->database('default', TRUE);
        $data = array(
            'title' => $title,
            'order' => $order,
            'content' => $content,
            'cate' => $cate
        );
        $db->where('id', $id);
        $result = $db->update('forwarding', $data);
        return $result;
    }

    function update_knowledge_article($id, $title, $content, $cate, $order) {
        if ($order <= 0) {
            $order = $id;
        }
        $db = $this->load->database('default', TRUE);
        $data = array(
            'title' => $title,
            'order' => $order,
            'content' => $content,
            'cate' => $cate
        );
        $db->where('id', $id);
        $result = $db->update('knowledge', $data);
        return $result;
    }

    //delete customs
    function _delete_customs_procedures($customs_id) {
        $db = $this->load->database('default', TRUE);
        $result = $db->delete('customs_procedures', array('customs_id' => $customs_id));
        return $result;
    }

    function delete_forwarding_article($id) {
        $db = $this->load->database('default', TRUE);
        $result = $db->delete('forwarding', array('id' => $id));
        return $result;
    }

    function delete_knowledge_article($id) {
        $db = $this->load->database('default', TRUE);
        $result = $db->delete('knowledge', array('id' => $id));
        return $result;
    }

}

?>